﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Drawing;

namespace Png2ico
{
    internal class Program
    {
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("请将.png文件拖动到图标上。");
            }
            else if (args.Length > 1)
            {
                Console.WriteLine("请勿拖动2个以上文件。");
            }
            else if (Path.GetExtension(args[0]).ToLower() != ".png")
            {
                Console.WriteLine("请将.png文件拖动到图标上，不要拖其他乱七八糟的文件。");
            }
            else
            {
                string saveDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
                string inputPath = args[0];
                string outputPath = saveDir + "/" + $"ICO-{DateTime.Now:yyyyMMddHHmmss}.ico";
                try
                {
                    // 加载PNG图像
                    using (Bitmap pngImage = new Bitmap(inputPath))
                    {
                        // 定义ICO支持的尺寸
                        List<Size> iconSizes = new List<Size>
                {
                    new Size(16, 16),
                    new Size(32, 32),
                    new Size(48, 48),
                    new Size(64, 64),
                    new Size(128, 128)
                };

                        // 创建多尺寸图标
                        using (MemoryStream memoryStream = new MemoryStream())
                        {
                            using (Icon icon = Icon.FromHandle(pngImage.GetHicon()))
                            {
                                icon.Save(memoryStream);
                            }

                            foreach (var size in iconSizes)
                            {
                                using (Bitmap resizedImage = new Bitmap(pngImage, size))
                                {
                                    using (Icon resizedIcon = Icon.FromHandle(resizedImage.GetHicon()))
                                    {
                                        resizedIcon.Save(memoryStream);
                                    }
                                }
                            }

                            // 保存为ICO文件
                            File.WriteAllBytes(outputPath, memoryStream.ToArray());
                        }
                    }

                    Console.WriteLine($"ICO file saved to: {outputPath}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error: {ex.Message}");
                }
            }


            Console.WriteLine();
            Console.WriteLine("按任意键退出...");
            Console.ReadKey();

        }
    }
}
